package com.whty.module.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.whty.common.annotation.Log;
import com.whty.common.base.AjaxResult;
import com.whty.common.enums.BusinessType;
import com.whty.common.support.Convert;
import com.whty.framework.web.page.TableDataInfo;

import com.whty.module.domain.Product;

import com.whty.module.service.IProductService;
import com.whty.system.domain.Garden;
import com.whty.system.domain.TagInfo;
import com.whty.system.service.IGardenService;
import com.whty.system.service.ITagInfoService;
import com.whty.system.service.ITagService;
import com.whty.web.core.base.BaseController;

/**
 * 标签 信息操作处理
 * 
 * @author mario
 * @date 2018-10-31
 */
@Controller
@RequestMapping("/module/tagInfo")
public class TagInfoController extends BaseController
{
    private String prefix = "module/tagInfo";
	
	@Autowired
	private ITagInfoService tagInfoService;
	@Autowired
	private ITagService iTagService;
	
	@Autowired
	private IProductService productService;
	@Autowired
	private IGardenService gardenService;
	private static Logger logger = LoggerFactory.getLogger(ProductDetailController.class);
	
	@RequiresPermissions("module:tagInfo:view")
	@GetMapping()
	public String tagInfo(ModelMap mmp)
	{
	    return prefix + "/tagInfo";
	}
	
	/**
	 * 查询标签列表
	 */
	@RequiresPermissions("module:tagInfo:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(TagInfo tagInfo)
	{
		startPage();
        List<TagInfo> list = tagInfoService.selectTagInfoList(tagInfo);
		return getDataTable(list);
	}
	
	/**
	 * 新增标签
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存标签
	 */
	@RequiresPermissions("module:tagInfo:add")
	@Log(title = "标签", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(TagInfo tagInfo)
	{	
		String companyName = "";
		if(!tagInfoService.dataValidation(tagInfo).equals("00")){
			return  error(tagInfoService.dataValidation(tagInfo));
		}
		String productCode = tagInfo.getProductCode();
		String gendenNo = tagInfo.getCompanyName();
		Garden garden = new Garden();
		garden.setTeaGardenNo(gendenNo);
		List<Garden> gardenList = gardenService.selectGardenList(garden);
		if(CollectionUtils.isNotEmpty(gardenList)){
			companyName = gardenList.get(0).getGardenName();
		}
//		tagInfo.setCompanyName(companyName);
		Product product = new Product();
		product.setProductCode(productCode);
		List<Product> productList = productService.selectProductList(product);
		if(productList != null && productList.size() > 0){
			Product product2 = productList.get(0);
			product2.setStatus("01");//溯源码已使用
			product2.setUpdateTime(new Date());
			productService.updateProduct(product2);
		}
		return toAjax(tagInfoService.insertTagInfo(tagInfo));
	}

	/**
	 * 修改标签
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		TagInfo tagInfo = tagInfoService.selectTagInfoById(id);
		/*
		 * 判断该标签信息 是否可以修改
		 */

	    String editInfo=iTagService.tagIsUse(tagInfo);
		
		mmap.put("editInfo", editInfo);
		mmap.put("tagInfo", tagInfo);
		if(editInfo.equals("false")){
			  return prefix + "/edit";
		}else{
			  return prefix + "/edit2";
		}
    
//		mmap.put("editInfo", "false");
	
	  
	}
	
	/**
	 * 修改保存标签
	 */
	@RequiresPermissions("module:tagInfo:edit")
	@Log(title = "标签", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(TagInfo tagInfo,String oldCode,String editInfo)
	{	
		logger.info("editInfo:"+editInfo);
		if(editInfo.equals("true")){
			String dealerName =tagInfo.getDealerName();
			String saleTime=tagInfo.getSaleTime();
			String remarks=tagInfo.getRemarks();
			tagInfo = tagInfoService.selectTagInfoById(tagInfo.getId());
			tagInfo.setSaleTime(saleTime);
//			if(dealerName.equals("")){
//				tagInfo.setDealerName(null);
//			}else{
//				tagInfo.setDealerName(dealerName);	
//			}
			tagInfo.setDealerName(dealerName);	
			tagInfo.setRemarks(remarks);
			if(!tagInfoService.dataValidation(tagInfo).equals("00")){
				return  error(tagInfoService.dataValidation(tagInfo));
			}
			
		}else{
			if(!tagInfoService.dataValidation(tagInfo).equals("00")){
				return  error(tagInfoService.dataValidation(tagInfo));
			}
			if(StringUtils.isNotBlank(oldCode) && !oldCode.equals(tagInfo.getProductCode())){ //如果更换了溯源码
				Product product = new Product();
				product.setProductCode(oldCode);
				List<Product> productList = productService.selectProductList(product);
				if(productList != null && productList.size() > 0){
					Product product2 = productList.get(0);
					product2.setStatus("00");//改回未使用
					product2.setUpdateTime(new Date());
					productService.updateProduct(product2);
				}
			}
			if(StringUtils.isNotBlank(tagInfo.getProductCode())){
				Product product = new Product();
				product.setProductCode(tagInfo.getProductCode());
				List<Product> productList = productService.selectProductList(product);
				if(productList != null && productList.size() > 0){
					Product product2 = productList.get(0);
					product2.setStatus("01");//溯源码已使用
					product2.setUpdateTime(new Date());
					productService.updateProduct(product2);
				}
			}
			tagInfo.setUpdateTime(new Date());
		}
		
		return toAjax(tagInfoService.updateTagInfo(tagInfo));
	}
	
	/**
	 * 删除标签
	 */
	@RequiresPermissions("module:tagInfo:remove")
	@Log(title = "标签", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		String[] idTemp=Convert.toStrArray(ids);
		for(int i=0;i<idTemp.length;i++){
			TagInfo tagInfo = tagInfoService.selectTagInfoById(Integer.parseInt(idTemp[i]));
			String isUse=iTagService.tagIsUse(tagInfo);
			if(isUse.equals("true")){
				return error("标签："+tagInfo.getTagQuence()+"已经发行了，不能删除");
			}
		}
		return toAjax(tagInfoService.deleteTagInfoByIds(ids));
	}
	
	/**
	 * 通过茶园编号查询标签信息
	 * @param teaGardenNo
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@PostMapping("/getTagInfo")
    @ResponseBody
	public List<Map>  getTagInfo(String teaGardenNo){
		logger.info("传入的茶园编号为："+teaGardenNo);
		Garden garden = new Garden();
		String companyName = "";
		List<Map> tagInfoData = new ArrayList<Map>();
		TagInfo tagInfo = new TagInfo();
    	if(StringUtils.isNotBlank(teaGardenNo)){
    		garden.setTeaGardenNo(teaGardenNo);
    		List<Garden> gardenList = gardenService.selectGardenList(garden);
    		if(CollectionUtils.isNotEmpty(gardenList)){
    			companyName = gardenList.get(0).getGardenName();
    		}
//    		tagInfo.setCompanyName(companyName);
    	}
    	List<TagInfo> tagInfoList = tagInfoService.selectTagInfoList(tagInfo);
    	if(CollectionUtils.isNotEmpty(tagInfoList)){
    		for (TagInfo tagInfo2 : tagInfoList) {
    			Map<String,String> map = new HashMap<String,String>();
    			map.put("id", tagInfo2.getId().toString());
    			map.put("tagInfo", tagInfo2.getTagQuence());
    			tagInfoData.add(map);
    		}
    	}
		return tagInfoData;
	}
}
